import { useCallback, useContext } from 'react'
import { useDispatch } from 'react-redux'
import { changeWidgets } from '@/store/modules/core'
import { ApiContext } from '@/api/ApiHub'
import { isEmpty } from 'loadsh'
import dayjs from 'dayjs'

const useQuery = () => {
  const dispatch = useDispatch()
  const api = useContext(ApiContext)

  const onWidgetsChange = useCallback((widgets) => dispatch(changeWidgets(widgets)), [dispatch])

  const setWidgets = (widgets, widgetId, query, status) => {
    const newWidgets = {
      ...widgets,
      [widgetId]: {
        ...widgets[widgetId],
        query,
        status
      }
    }
    onWidgetsChange(newWidgets)
  }

  const chartQuery = async (widgets, widgetId, widgetQuery) => {
    const status = {
      loading: false,
      error: null,
      data: null,
      updateTime: null
    }
    const widget = widgets[widgetId]
    const query = widgetQuery || widget?.query
    if (isEmpty(query?.queryFields)) {
      setWidgets(widgets, widgetId, query, status)
      return
    }
    setWidgets(widgets, widgetId, query, { ...status, loading: true })
    const stateStatus = { ...status }
    try {
      const { data } = await api.queryData(query)
      stateStatus.data = data
    } catch (error) {
      stateStatus.error = error
    }
    setWidgets(widgets, widgetId, query, {
      ...stateStatus,
      loading: false,
      updateTime: dayjs().format('YYYY-MM-DD HH:mm:ss')
    })
  }

  const allChartQuery = (widgets) => {
    Object.entries(widgets).forEach(async ([id, widget]) => {
      chartQuery(widgets, id, widget?.query)
    })
  }

  return { setWidgets, chartQuery, allChartQuery }
}

export default useQuery
